﻿import plugin from '../../../lib/plugins/plugin.js'
import lodash from 'lodash'
import fetch from 'node-fetch'
import gsCfg from '../../genshin/model/gsCfg.js'
import YAML from "yaml";
import {createRequire} from "module";
const require = createRequire(import.meta.url);
const fs =require('fs')
import { Config } from '../components/index.js'

export class genshinRegTime extends plugin {
constructor () {
super({
name: '原神注册时间查询',
dsc: '从原神绘忆星辰活动获取游戏注册时间。',
event: 'message',
priority: 1999,
rule: [
{
reg: '^#?(刷新)?(我的|原神)?注册时间$',
fnc: 'getQueryRegTime'
}
]
})
}

async getQueryRegTime () {
let set = await Config.admin_set
let isplugin = set.genshintime
if (!isplugin) return false
let result = await this.queryMysCk()
if (result.code !== 1) {
await this.e.reply(result.msg)
return true
}
let ckList = result.data; ckList = ckList || []
let queryList = []
let cookie = ''
for (let ck of ckList) {
if (ck.ck) {
cookie = ck.ck
}
queryList.push(await this.queryRegTime(cookie, ck.uid))
}
this.reply(`\n---原神注册时间---\r\n${queryList.join('\r\n----------------\r\n')}\n如需更新数据，请发送 #刷新注册时间`,false, { at: true })
return true
}

async queryRegTime (mysCookies, uid) {
let result = await this.getGameData(mysCookies, uid)
if (result?.code === 1 && result.infoData && result.gameData) {
let level = result.infoData.level
let nickname = result.infoData.nickname
let regionName = result.infoData.region_name
let data = result.gameData.data?.data
data = data ? JSON.parse(data) : {}
let regTime = data['1']
if (regTime > 0) {
regTime = new Date(regTime * 1000 + 28800000).toJSON().split('T').join(' ').split('.')[0]
} else {
regTime = '查询失败！'
}
let queryTime = new Date(result.queryTime + 28800000).toJSON().split('T').join(' ').split('.')[0]
return `uid：${nickname}(${uid})\r\n服务器：${regionName}\r\n冒险等级：${level}\r\n注册时间：${regTime}\r\n查询时间：${queryTime}`
}
let msg = result.msg
msg = msg || '查询失败！'
return `uid：${uid}\r\n注册时间：${msg}`
}

async getGameData (mysCookies, uid) {
let msg = ''
let gameData = null
let tempData = {}
const key = `Yz:genshin-RegTime:${this.e.user_id}`
if (await redis.exists(key)) {
tempData = JSON.parse(await redis.get(key))
}
if (tempData && tempData[uid] && tempData[uid].gameData && tempData[uid].infoData && !this.e.msg.includes('刷新')) {
gameData = tempData[uid]
}
if (!gameData || (new Date().getTime() - gameData.queryTime) > (1000 * 60 * 60 * 6) || this.e.msg.includes('刷新') || !await redis.exists(key)) {
let result = await this.updateGameData(mysCookies, uid)
if (result.code == 1 && result.data) {
let saveData = tempData || {}
saveData[uid] = result.data
await redis.set(key, JSON.stringify(saveData))
gameData = result.data
} else {
msg = result.msg
}
}

if (gameData) {
return { code: 1, msg, ...gameData }
}
msg = msg || '查询失败！'
return { code: -1, msg }
}

async updateGameData (mysCookies, uid) {
let msg = ''
let result = await this.hk4eCnLogin(mysCookies, uid)
if (result.code == 1) {
let infoData = result.data.data?.data; infoData = infoData || null
let options = {
method: 'GET',
headers: {
Cookie: result.data.cookies.join('; ')
}
}
let api = 'https://hk4e-api.mihoyo.com'
let region = infoData.region; region = region || ''
if (region.includes('os_')) {
api = 'https://sg-hk4e-api.hoyoverse.com'
}
let url = `${api}/event/e20220928anniversary/game_data?badge_uid=${uid}&badge_region=${infoData.region}&lang=zh-cn&game_biz=${infoData.game_biz}`
let response = await fetch(url, options)
try {
let res = await response.json()
let data = res.data?.data
if (infoData && data) {
return {
code: 1,
msg,
data: { gameData: res, infoData, queryTime: new Date().getTime() }
}
} else {
msg = res.message
}
} catch (err) { }
} else {
msg = result.msg
}
msg = msg || '查询失败！'
return { code: -1, msg }
}

async hk4eCnLogin (mysCookies, uid) {
let api = 'https://api-takumi.mihoyo.com'
let body = { game_biz: 'hk4e_cn', lang: 'zh-cn', region: 'cn_gf01', uid: '' }
body.region = await this.getServer(uid)
body.uid = uid
if (body.region.includes('os_')) {
body.game_biz = 'hk4e_global'
api = 'https://sg-public-api.hoyoverse.com'
}
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: mysCookies
},
body: JSON.stringify(body)
}
let url = `${api}/common/badge/v1/login/account`
let response = await fetch(url, options)
let cookies = []
let code = -1
let msg = ''
let result = null
try {
let headers = response.headers
let SetCookie = headers.getAll('set-cookie')
for (let index in SetCookie) {
let cookie = SetCookie[index]
let reg = /(.*?);/.exec(cookie)
if (reg && reg.length > 1) {
cookie = reg[1]
let arr = cookie.split('=')
if (arr.length > 1 && arr[1] != '') {
if (arr[0] == 'e_hk4e_token') {
code = 1
}
cookies.push(cookie)
}
}
}
let res = await response.json()
result = { cookies, data: res }
msg = res.message
} catch (err) { }
return { code, msg, data: result }
}

async queryMysCk () {
let cks = gsCfg.getBingCkSingle(this.e.user_id)
if (lodash.isEmpty(cks)) {
return { code: -2, msg: '请先绑定Cookie' }
}
let list = []
for (let uid in cks) {
let ck = cks[uid]
if (!lodash.isEmpty(ck)) {
list.push(ck)
}
}
if (list.length < 1) {
return { code: -1, msg: '获取Cookie失败！' }
}
return { code: 1, msg: '获取成功！', data: list }
}

async getServer (uid) {
switch (String(uid)[0]) {
case '1':
case '2':
return 'cn_gf01' // 官服
case '5':
return 'cn_qd01' // B服
case '6':
return 'os_usa' // 美服
case '7':
return 'os_euro' // 欧服
case '8':
return 'os_asia' // 亚服
case '9':
return 'os_cht' // 港澳台服
}
return 'cn_gf01'
}
}
